package com.newgrand.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.newgrand.domain.model.I8ReturnModel;
import com.newgrand.domain.model.PurchasePlan;
import com.newgrand.domain.model.RequestResult;
import com.newgrand.service.PurchasePlanService;
import com.newgrand.utils.*;
import com.newgrand.utils.i8util.I8Converter;
import com.newgrand.utils.i8util.I8Request;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @创建人：ZhaoFengjie
 * @修改人：ZhaoFengjie
 * @创建时间：15:23 2022/10/11
 * @修改时间:：15:23 2022/10/11
 */
@Service
public class PurchasePlanImpl extends GetPhIdHelper implements PurchasePlanService {

    //private static final String accessId = YamlConstants.getPropertiesKey("accessId");// "hzBAPK6dbFdKULHGejvT";
    //private static final String secretKey = YamlConstants.getPropertiesKey("secretKey");//"1IbaS54b/jqdrQKvEOcfgpGIdzseW26ZBMxHSAdc";
    //private static final String baseUrl = YamlConstants.getPropertiesKey("baseUrl");//"https://api.mctech.vip";
    private static final OpenApiClient client = new OpenApiClient(YamlConstants.getPropertiesKey("yl.baseUrl"), YamlConstants.getPropertiesKey("yl.accessId"), YamlConstants.getPropertiesKey("yl.secretKey"));
    private static final String pcrApi = "/api/mquantity/query-purchase-plan-params?orgId=%d&version=%d&limit=%d&offset=%d";
    private static final Logger logger = LogManager.getLogger(PurchasePlanImpl.class);
    @Resource
    private I8Request i8Request;
    private static final NGLog ngLog = new NGLog();

    private static final String mstformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"UserCode\":\"202210170003\",\"UserTitle\":\"采购计划测试\",\"PhidPc\":\"\",\"PStartDt\":\"2022-10-17\",\"PhidWbs\":\"\",\"PhidVendorid\":\"\",\"PhidDept\":\"\",\"PhidPlanpsn\":\"\",\"PhidPlantype\":\"\",\"PhidCgtype\":\"\",\"PhidCntid\":\"\",\"HtAmt\":\"\",\"PhidCycle\":\"\",\"OriMoney\":0,\"UntaxamtFc\":0,\"OriTaxamt\":0,\"TaxamtFc\":0,\"Remarks\":\"\",\"TotalAmt\":\"0\",\"Qrcode\":\"\",\"PhidRegion\":\"\",\"PhidCurr\":\"1\",\"ExchRate\":1,\"PhId\":\"\",\"NgRecordVer\":\"\",\"PhidFillpsn\":\"\",\"PhidApppsn\":\"\",\"PhidOcode\":\"169220606000002\",\"ChkFlg\":\"0\",\"PhidSchemeId\":\"169220617002008\",\"ImpInfo\":\"\",\"WfFlg\":\"\",\"DaFlg\":\"\",\"AsrFlg\":\"\",\"PointId\":\"\",\"IsClose\":\"\",\"Creator\":\"\",\"PrintCount\":\"\",\"ListFilterVal\":\"\",\"QueryField1Val\":\"\",\"QueryField2Val\":\"\",\"UIMultiConfigID\":\"\",\"PhidTask\":\"\",\"key\":\"\"}}}";
    private static final String matpdgridData = "{\"Lineid\":0,\"PhId\":\"\",\"Pphid\":\"\",\"PhidPc\":\"\",\"PhidPc_EXName\":\"\",\"PhidItemid\":\"\",\"PhidItemid_EXName\":\"\",\"OrderQty\":10,\"Qty\":10,\"ReqQty\":0,\"Taxprc\":0,\"Untaxprc\":0,\"Taxrate\":0,\"Tax\":0,\"Taxamt\":0,\"OriUntaxamt\":0,\"Untaxamt\":0,\"PhidVendorid\":\"\",\"PhidVendorid_EXName\":\"\",\"PhidBoq\":\"\",\"PhidBoq_EXName\":\"\",\"BoqCode\":\"\",\"BoqDes\":\"\",\"PhidWbs\":\"\",\"PhidWbs_EXName\":\"\",\"PhidCbs\":\"\",\"PhidCbs_EXName\":\"\",\"ResPropertys\":\"\",\"Remarks\":\"\",\"Source\":\"0\",\"PhidSrcid\":\"\",\"PhidSrcdid\":\"\",\"TaxprcFc\":0,\"UntaxprcFc\":0,\"TaxamtFc\":0,\"UntaxamtFc\":0,\"PhidCurr\":\"1\",\"PhidCurr_EXName\":\"人民币\",\"ExchRate\":1,\"OriQty\":10,\"OriPrc\":0,\"OriMoney\":0,\"OriTaxrate\":0,\"OriTax\":0,\"OriTaxamt\":0,\"OriTaxprc\":0,\"UsedQty\":0,\"PhidResBs\":\"\",\"PhidResBs_EXName\":\"\",\"PhidResBs_Code\":\"\",\"PhidItemData\":\"\",\"PhidItemData_EXName\":\"\",\"ImpInfo\":\"\",\"AsrFlg\":\"\",\"Guid\":\"\",\"PurchasementType\":0,\"IsFarmProduce\":0,\"IsClose\":\"\",\"IsCloseStatus\":\"\",\"PhidCloser\":\"\",\"PhidCloser_EXName\":\"\",\"CloseDt\":null,\"CollectID\":\"\",\"ImpTaxrate\":0,\"ResDescript\":\"\",\"NgRecordVer\":0,\"ItemDataNo\":\"\",\"ItemDataName\":\"\",\"Spec\":\"\",\"PhidUnit\":\"\",\"UnitName\":\"\",\"MainMat\":\"\",\"ItemPropGrpName\":\"\",\"ResMasterData\":\"\",\"UmConv\":0,\"UmConvm\":0,\"FzMsname\":\"\",\"FzMsAmount\":0,\"FzMsPrice\":0,\"TempAsrFlg\":\"\",\"key\":null}";

    @Async(value = "asyncServiceExecutor")
    @Override
    public void saveBatch(List<PurchasePlan.PurchasePlanData> data, String orgId) {
        for (PurchasePlan.PurchasePlanData item : data) {
            save(item, orgId);
        }
    }

    /**
     * 对应i8采购计划
     *
     * @param data
     * @return
     */
    @Override
    public I8ReturnModel<String> save(PurchasePlan.PurchasePlanData data, String orgId) {
        try {
            ngLog.info("PurchasePlanImpl", "采购计划报文->" + JSON.toJSONString(data));
            String PhidPc = GetPhIdByCode("project_table", "user_mcxmid", orgId);//pcNo

            //String PhidCnt = GetPhIdByCode("fg3_enterprise", "compname", data.get);

            HashMap<String, Object> map = new HashMap<>();
            map.put("PhidVendorid", "");
            map.put("UserTitle", data.getPlanName());
            map.put("UserCode", data.getOrderCode());
            map.put("OriTaxamt", data.getTotalAmount());
            map.put("HtAmt", data.getTotalAmount());
            map.put("Remarks", data.getRemark());
            map.put("PStartDt", data.getMakerDate());
            map.put("UntaxamtFc", data.getTotalAmount());

            List<PurchasePlan.PurchasePlanDataItem> detail = data.getItems();
            ArrayList<HashMap<String, Object>> itemList = new ArrayList<>();
            for (PurchasePlan.PurchasePlanDataItem item : detail) {
                HashMap<String, Object> itemData = new HashMap<>();
                itemData.put("OrderQty", item.getQuantity());
                itemData.put("OriQty", item.getQuantity());
                itemData.put("Qty", item.getQuantity());
                itemData.put("OriTaxprc", item.getPurchasePrice());
                itemData.put("TaxprcFc", item.getPurchasePrice());
                itemData.put("OriPrc", item.getPurchasePrice());
                itemData.put("UntaxprcFc", item.getPurchasePrice());
                itemData.put("OriMoney", item.getPurchaseSum());
                itemData.put("UntaxamtFc", item.getPurchaseSum());
                itemData.put("OriTaxamt", item.getPurchaseSum());
                itemData.put("TaxamtFc", item.getPurchaseSum());
                itemList.add(itemData);
            }

            List<NameValuePair> formdata = new ArrayList<>();
            formdata.add(new BasicNameValuePair("mstformData", I8Converter.SetField(mstformData, map)));
            formdata.add(new BasicNameValuePair("matpdgridData", I8Converter.SetTableRow(matpdgridData, itemList)));
            formdata.add(new BasicNameValuePair("matpcollectData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("schemeid", "169220617002008"));
            formdata.add(new BasicNameValuePair("isContinue", "false"));
            formdata.add(new BasicNameValuePair("attchmentGuid", "0"));
            formdata.add(new BasicNameValuePair("ng3_logid", "0"));
            I8ReturnModel<String> res = i8Request.PostFormSyncByOcode("/PMS/PMM/MatPM/save", formdata, "101");
            if(res.getIsOk()){
                return I8ReturnModel.success();
            }
            throw new RuntimeException(res.getMessage());
        } catch (Exception ex) {
            ngLog.error("PurchasePlanImpl", "采购计划保存异常", ex.getMessage());
            return I8ReturnModel.error(ex.getMessage());
        }
    }

    @Override
    public List<PurchasePlan.PurchasePlanData> getData(String orgId) {
        //        String orgId = "";//组织机构id
        Integer offset = 0;//从第N条开始
        Integer limit = 100;//
        List<PurchasePlan.PurchasePlanData> dataList = new ArrayList<>();
        Long version = 0L;//本次请求所要获取的增量数据的version起始值，客户端需要存储接口返回的数据集合中最后一条数据version值
        Long orgIdL = Long.parseLong(orgId);
        while (true) {
            try {
                String apiUrl = String.format(pcrApi, orgIdL, version, limit, offset);
                RequestResult dataBody = client.post(apiUrl, "");
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                PurchasePlan res = JSONObject.parseObject(content, PurchasePlan.class);
                List<PurchasePlan.PurchasePlanData> dataArray = res.getData();
                int count = dataArray.size();
                dataList.addAll(dataArray);
                if (count < limit) {
                    break;
                }
                offset = offset + limit;
//                version = dataArray.get(count - 1).getVersion();
            } catch (Exception ex) {
                logger.info(String.format("call api error:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public I8ReturnModel<List<PurchasePlan.PurchasePlanData>> getDataByOrgId(String orgId) {
        return I8ReturnModel.success("获取数据成功", getData(orgId));
    }

    @Override
    public I8ReturnModel<String> saveDataByOrgId(String orgId) {
        List<PurchasePlan.PurchasePlanData> data = getData(orgId);
        if (!data.isEmpty()) {
            saveBatch(data, orgId);
        } else {
            return I8ReturnModel.success(orgId + "-项目，未获取的需要同步的数据");
        }
        return I8ReturnModel.success();
    }
}
